<?php

class AliyunClient {
    //构造函数
    public function __construct($accessKeyId, $accessKeySecret, $Action) {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->Action = $Action;
    }
    public $Action;
    public $accessKeyId;
    public $accessKeySecret;
    const SERVERURL = 'http://dns.aliyuncs.com/';
    const FORMAT = 'json';
    const SIGNATUREMETHOD = 'HMAC-SHA1';
    const SIGNATUREVERSION = '1.0';
    const DATETIMEFORMAT = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
    const VERSION = '2015-01-09';
    public function execute() {
        $PublicParams["AccessKeyId"] = $this->accessKeyId;
        $PublicParams["Format"] = self::FORMAT;
        $PublicParams["SignatureMethod"] = self::SIGNATUREMETHOD;
        $PublicParams["SignatureVersion"] = self::SIGNATUREVERSION;
        $PublicParams["SignatureNonce"] = $this->CreateSignatureNonce();
        date_default_timezone_set("UTC");
        $PublicParams["TimeStamp"] = date(self::DATETIMEFORMAT);
        $PublicParams["Version"] = self::VERSION;
        $PublicParams["Action"] = $this->Action;
        $PublicParams["Signature"] = $this->computeSignature($PublicParams, $this->accessKeySecret);

        $requestUrl = rtrim(self::SERVERURL, "/") . "/?";
        foreach ($PublicParams as $ParamKey => $ParamValue) {
            $requestUrl .= "$ParamKey=" . urlencode($ParamValue) . "&";
        }
        $requestUrl = substr($requestUrl, 0, -1);
        return (string) $requestUrl;
    }
//UUID随机唯一ID
    public function CreateSignatureNonce() {
        mt_srand((double) microtime() * 10000);
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);
        $uuid = chr(123)
                . substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12)
                . chr(125);
        return $uuid;
    }
    public function percentEncode($str) {
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }
//计算签名
    public function computeSignature($parameters, $accessKeySecret) {
        ksort($parameters);
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key)
                    . '=' . $this->percentEncode($value);
        }
        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
        return $signature;
    }
}